package com.seek.service.imp;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.seek.core.BaseServiceImpl;
import com.seek.dao.CompanyAgentDao;
import com.seek.model.entity.TCompanyAgent;
import com.seek.service.CompanyAgentService;
import com.seek.util.BeanUtils;
import com.seek.util.CommonUtil;

@Repository("companyAgentService")
public class CompanyAgentServiceImpl extends BaseServiceImpl<TCompanyAgent> implements CompanyAgentService {

	@Autowired
	public void setDao(CompanyAgentDao companyAgentDao) {
		super.setDao(companyAgentDao);
	}
	public CompanyAgentDao getDao() {
		return (CompanyAgentDao) super.getDao();
	}
	
	@Transactional
	public TCompanyAgent save(JSONObject reqJson) throws Exception{
		TCompanyAgent en = new TCompanyAgent();
		if (CommonUtil.getLongValue((reqJson.getString("agentId")))>0){
			en.setId(CommonUtil.getLongValue(reqJson.getString("agentId")));
		}
		en.setCompanyId(reqJson.getLong("companyId"));
		en.setAgentName(reqJson.getString("agentName"));
		en.setPhoneNo(reqJson.getString("phoneNo"));
		en.setMoneyType(CommonUtil.getIntValue(reqJson.getString("moneyType")));
		en.setMoney(CommonUtil.getIntValue(reqJson.getString("money")));
		en.setBankName(reqJson.getString("bankName"));
		en.setCardNumber(reqJson.getString("cardNumber"));
		en.setRemark(reqJson.getString("remark"));
		en.setFid(reqJson.getLong("fid"));
		
		if (CommonUtil.isEmpty(en.getAgentName()) || CommonUtil.isEmpty(en.getPhoneNo()) || en.getMoneyType()<1 || en.getMoney()<1 || CommonUtil.isEmpty(en.getBankName()) || CommonUtil.isEmpty(en.getCardNumber())){
			throw new Exception("缺少必须的参数，请检查");
		}
		
		if (en.getId() == null || en.getId() < 1){
			en.setIsUsed(1);
			en.setCreateTime(new Date());
			en.setCreateUserId(CommonUtil.getLongValue(reqJson.getString("_currnetUserId")));
			en.setModifyTime(new Date());
			en.setModifyUserId(en.getCreateUserId());
			en = this.getDao().insert(en);
		}else{
			en.setModifyTime(new Date());
			en.setModifyUserId(CommonUtil.getLongValue(reqJson.getString("_currnetUserId")));
			TCompanyAgent old = this.getDao().get(en.getId());
			BeanUtils.copyPropertiesExclude(en, old, new String[]{"id","companyId","createUserId","createTime","isUsed"});
			en = this.getDao().update(old);	
		}

		return en;
	}
}